<?php

class Application_Model_UserMapper extends Dealscombined_Db_Mapper_MapperAbstract {
	/**
	 * The class name of the DB Table.
	 *
	 * @var string
	 */
	protected $_dbTable = 'Application_Model_DbTable_User';

	/**
	 * The class name of the DB Model.
	 *
	 * @var string
	 */
	protected $_dbModel = 'Application_Model_User';

	/**
	 * The name of the cookie for verification
	 *
	 * @var string
	 */
	protected $_cookieName = '_DCUKID';

	/**
	 * Fields that are part of the model but are not in the same table or database
	 *
	 * @var array
	 * */
	protected $_nonTableFields = array('facebook_profile','log_out_url','log_in_url');
	
	

	public function findByEMail(Application_Model_User $user) {
		$result = $this->fetchAll(array('email = ?' => $user -> getEmail()));
		if (0 == count($result)) {
			$entry = null;
		} else {	
			$entry = $result[0];
		}
		return $entry;
	}

	public function authenticate($email = null, $cityId = null) {
		
     	$nameSpace = new Zend_Session_Namespace('Dealscombined');
		$cookieName = $this->_cookieName;
 		$entry = null;
		
 		if (isset($nameSpace->$cookieName)){
 			
			$magic = $nameSpace->$cookieName;
 			$result = $this-> fetchAll(array('magic = ?' => $magic), null, 1);			
			
			if (0 < count($result)){
				$entry = $result[0];				
			}	
			else{
				$entry = null;
			}		
 		}
		
		//If not found or not logged before
		if (is_null($entry)){
			$entry    = new $this->_dbModel();
			$strNewMagic = $entry->generateMagic();	
			$nameSpace->$cookieName = $strNewMagic;			
			$entry->setMagic($strNewMagic);	
		}
		
		if (!is_null($email)){
			$entry->setEmail($email);
		}
		
		if (!is_null($cityId)){
			$entry->setCityId($cityId);
		}
			
		$entry->touch();	
		try{
			$this->_save($entry);
		}
		catch(Exception $e){
			//email exist
			if (strpos($e->getMessage(),'Duplicate entry') !== false) {
					$newEntry = $this->findByEMail($entry);
					$newEntry->setMagic($entry->getMagic());
					$newEntry->touch();
					$this->_save($newEntry);
					$entry = $newEntry;
			}
			else{
				throw $e;
			}
		}		
		return $entry;
	}

}
